import React, { useEffect } from 'react';
import { View, Image,Text, TouchableOpacity, StyleSheet ,ImageBackground,Dimensions,Alert,ScrollView,TextInput,Button,Modal,} from 'react-native';
import { NavigationContainer, RouteProp, useNavigation } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import {useState} from 'react';
import { NavigationScreenProp } from 'react-navigation';
import SuccessScreen from './SuccessScreen';
import ConfettiCannon from 'react-native-confetti-cannon';
import { FlatList } from 'react-native-gesture-handler';
import Dialog from 'react-native-dialog';
import {useRoute} from '@react-navigation/native';
import axios from 'axios';
import SQLite from 'react-native-sqlite-storage';



const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
let isDataFetched = false;
let buttonIndex=0;

const YourCustomFont = require('./LiuJianMaoCao-Regular.ttf');

const Stack = createStackNavigator();

interface Props {
  navigation: NavigationScreenProp<any, any>;
}


interface CustomButtonProps {
  title: string;
  onPress: () => void; // onPress 属性应该是一个接受空参数并返回 void 的函数类型
}

const CustomButton: React.FC<CustomButtonProps> = ({ title, onPress }) => {
  return (
    <TouchableOpacity style={styles.button3} onPress={onPress}>
      <Text style={styles.buttonText3}>{title}</Text>
    </TouchableOpacity>
  );
};
//---------------------------------------------------------------随机选择
//---------------------------------------------------------------清汤-奇幻
const Random_ClearFantasyScreen = ({navigation}: Props) => {
  type Message = {
    sender: string;
    text: string;
  };
  const [conversation, setConversation] = useState<Message[]>([]);
  const [message, setMessage] = useState('');//存储用户对话框输入
  const [showPromptBox, setShowPromptBox] = useState(false);//“提示”框
  const [showModal, setShowModal] = useState(false);//还原答案框
  const [showModal2, setShowModal2] = useState(false);//成功框
  const [showModal3, setShowModal3] = useState(false);//失败框
  const [showResult, setResult] = useState(false);//结果框
  const [message2, setMessage2] = useState('');//存储用户还原答案输入
  const [errorCount, setErrorCount] = useState(0);
  // 控制还原答案框显示与否
  const handleOpenModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setShowModal(false);
  };
  // 控制成功答案框显示与否
  const handleOpenModal2 = () => {
    setShowModal2(true);
  };
  const handleCloseModal2 = () => {
    setShowModal2(false);
    navigation.navigate('Soup');
  };
  // 控制失败答案框显示与否
  const handleOpenModal3 = () => {
    setShowModal3(true);
  };
  const handleCloseModal3 = () => {
    setShowModal3(false);
    navigation.navigate('Soup');
  };
  // 提示框界面
  const showAlert = async () => {
    console.log('ok');
    try {
      const requestData = { message: '我需要获得提示' }; // 构造请求数据
      const jsonData = JSON.stringify(requestData);

      const response = await fetch('localhost:5000/receive_data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonData,
      });

      if (response.ok) {
        const responseData = await response.json();
        const processedData = responseData.response;

        // 将后端返回的结果显示在提示框中
        Alert.alert(
          '提示',
          `您获得的提示是：${processedData}`,
          [
            {
              text: '得到提示！<(￣︶￣)↗[GO!]',
              onPress: () => setShowPromptBox(false),
            },
          ],
          {
            cancelable: false,
          },
        );
      } else {
        console.error('Request failed with status:', response.status);
      }
    } catch (error) {
      console.error('Request failed with error:', error);
    }
  };
  //结果框界面
  const showresult = () => {
    const requestData = {
      message: message2,
    };
    let text2 = ' ';
    // 发送 POST 请求给后端
    fetch('http:/10.0.2.2:5000/guess', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData),
    })
      .then(response => response.json())
      .then(data => {
        // 处理后端返回的响应
        const response = JSON.stringify(data.response);
        // 更新前端的 text1
        text2 = response;
        const ifwin = data.response.substr(0, 4); // 只取前四个字
        setMessage2('');
        handleCloseModal();
        Alert.alert(
          `结果 您剩余的验证次数为 ${2 - errorCount}`,
          text2,
          [
            {
              text: '得到结果！<(￣︶￣)↗[GO!]',
              onPress: () => {
                if (ifwin === '回答正确') {
                  handleOpenModal2();
                } else if (ifwin === '回答错误') {
                  setResult(false);
                  if (errorCount >= 2) {
                    setErrorCount(0);
                    handleOpenModal3();
                  } else {
                    setErrorCount(errorCount + 1);
                  }
                }
              },
            },
          ],
          {
            cancelable: false,
          },
        );
      })
      .catch(error => {
        console.error('Error:', error);
      });
  };
  // 用户输入信息函数，与后台chatwithvivo函数连接
  const sendMessage = async () => {
    if (message) {
      const data = {message: message};
      const jsonData = JSON.stringify(data);
      try {
        const response = await fetch('http:/10.0.2.2:5000/receive_data', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: jsonData,
        });
        type Message = {
              sender: string;
              text: string;
            };
        if (response.ok) {
          const responseData = await response.json();
          const processedData = responseData.response;

          setConversation([
            ...conversation,
            { sender: 'user', text: message },
            { sender: 'bot', text: processedData },
          ]);
          setMessage('');
        } else {
          console.error('Request failed with status:', response.status);
        }
      } catch (error) {
        console.error('Request failed with error:', error);
      }
    }
  };

  const [data, setData] = useState<YourData[]>([]);
  const fetchData = async () => {
    try {
      if (!isDataFetched) {
        const response = await fetch('http:/10.0.2.2:5000/random_clearfantasy');
        const jsonData = await response.json();
        setData(jsonData);
        isDataFetched = true;
        console.log(isDataFetched);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
  fetchData();
  interface YourData {
    soup_surface: string; // 假设 column1 是一个字符串
    // 可以添加其他列...
  }
  return (
    <View style={styles.container}>
      {/* 汤面固定 */}
      <View style={styles.header}>
         {data.map((item, index) => (
           <Text style={styles.headerText} key={index}>
             {item.soup_surface}
           </Text>
         ))}
       </View>
      {/* 滚动屏 */}
      <ScrollView style={styles.conversation}>
        {/* 灰字提示部分 */}
        <View style={styles.welcomeContainer}>
          <Text style={styles.welcomeText}>欢迎进入海龟汤的游戏</Text>
          <Text style={styles.ruleText}>游戏中请注意以下规则：</Text>
          <Text style={styles.ruleText}>
            1. 根据汤面可以向主持人提问，尽量清楚描述问题，注意只会回答你是/否/与此无关
          </Text>
          <Text style={styles.ruleText}>
            2. 如果需要验证汤底，请点击下方的还原答案按钮。不过，你只有三次验证机会
          </Text>
          <Text style={styles.ruleText}>下面，你可以开始进行提问+猜测了！</Text>
          <Text style={styles.ruleText}>-------------------------</Text>
        </View>
        {/* 对话框 */}
        {conversation.map((item, index) => (
          <View
            key={index}
            style={
              item.sender === 'user' ? styles.userMessage : styles.botMessage
            }>
            <Text>{item.text}</Text>
          </View>
        ))}
      </ScrollView>
      {/* 还原答案和提示按钮 */}
      <View style={styles.answerButton}>
        <CustomButton title="还原答案" onPress={handleOpenModal} />
        <CustomButton title="提示" onPress={showAlert} />
      </View>
      {/* 底部输入框 */}
      <View style={styles.inputBox}>
        <TextInput
          style={styles.input}
          placeholder="请输入内容"
          value={message}
          onChangeText={text => setMessage(text)}
        />
        <CustomButton title="发送" onPress={sendMessage} />
      </View>
      {/* 汤面还原框 */}
      <Modal visible={showModal} animationType="slide" transparent={true}>
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <TextInput
              style={styles.input_guessstory}
              placeholder="请在此处还原你的汤面..."
              value={message2}
              textAlignVertical="top"
              multiline={true}
              onChangeText={text => setMessage2(text)}
            />
            <View style={styles.buttonbox}>
              <CustomButton title="发送" onPress={showresult} />
              <CustomButton title="返回" onPress={handleCloseModal} />
            </View>
          </View>
        </View>
      </Modal>
      {/* 成功框 */}
      <Modal visible={showModal2} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>成功</Text>
          <Image
            source={require('./bear.jpg')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal2} />
          <ConfettiCannon
            count={100}
            origin={{x: -10, y: 0}}
            explosionSpeed={300}
            fallSpeed={2000}
            colors={['#ff0000', '#00ff00', '#0000ff']}
          />
        </View>
      </Modal>
      {/* 失败框 */}
      <Modal visible={showModal3} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>失败</Text>
          <Image
            source={require('./bear2.gif')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal3} />
        </View>
      </Modal>
    </View>
  );
};
//---------------------------------------------------------------清汤-搞笑
const Random_ClearFunnyScreen = ({navigation}: Props) => {
  type Message = {
    sender: string;
    text: string;
  };
  const [conversation, setConversation] = useState<Message[]>([]);
  const [message, setMessage] = useState('');//存储用户对话框输入
  const [showPromptBox, setShowPromptBox] = useState(false);//“提示”框
  const [showModal, setShowModal] = useState(false);//还原答案框
  const [showModal2, setShowModal2] = useState(false);//成功框
  const [showModal3, setShowModal3] = useState(false);//失败框
  const [showResult, setResult] = useState(false);//结果框
  const [message2, setMessage2] = useState('');//存储用户还原答案输入
  const [errorCount, setErrorCount] = useState(0);
  // 控制还原答案框显示与否
  const handleOpenModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setShowModal(false);
  };
  // 控制成功答案框显示与否
  const handleOpenModal2 = () => {
    setShowModal2(true);
  };
  const handleCloseModal2 = () => {
    setShowModal2(false);
    navigation.navigate('Soup');
  };
  // 控制失败答案框显示与否
  const handleOpenModal3 = () => {
    setShowModal3(true);
  };
  const handleCloseModal3 = () => {
    setShowModal3(false);
    navigation.navigate('Soup');
  };
  // 提示框界面
  const showAlert = async () => {
    console.log('ok');
    try {
      const requestData = { message: '我需要获得提示' }; // 构造请求数据
      const jsonData = JSON.stringify(requestData);

      const response = await fetch('http://10.0.2.2:5000/receive_data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonData,
      });

      if (response.ok) {
        const responseData = await response.json();
        const processedData = responseData.response;

        // 将后端返回的结果显示在提示框中
        Alert.alert(
          '提示',
          `您获得的提示是：${processedData}`,
          [
            {
              text: '得到提示！<(￣︶￣)↗[GO!]',
              onPress: () => setShowPromptBox(false),
            },
          ],
          {
            cancelable: false,
          },
        );
      } else {
        console.error('Request failed with status:', response.status);
      }
    } catch (error) {
      console.error('Request failed with error:', error);
    }
  };
  //结果框界面
  const showresult = () => {
    const requestData = {
      message: message2,
    };
    let text2 = ' ';
    // 发送 POST 请求给后端
    fetch('http:/10.0.2.2:5000/guess', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData),
    })
      .then(response => response.json())
      .then(data => {
        // 处理后端返回的响应
        const response = JSON.stringify(data.response);
        // 更新前端的 text1
        text2 = response;
        const ifwin = data.response.substr(0, 4); // 只取前四个字
        setMessage2('');
        handleCloseModal();
        Alert.alert(
          `结果 您剩余的验证次数为 ${2 - errorCount}`,
          text2,
          [
            {
              text: '得到结果！<(￣︶￣)↗[GO!]',
              onPress: () => {
                if (ifwin === '回答正确') {
                  handleOpenModal2();
                } else if (ifwin === '回答错误') {
                  setResult(false);
                  if (errorCount >= 2) {
                    setErrorCount(0);
                    handleOpenModal3();
                  } else {
                    setErrorCount(errorCount + 1);
                  }
                }
              },
            },
          ],
          {
            cancelable: false,
          },
        );
      })
      .catch(error => {
        console.error('Error:', error);
      });
  };
  // 用户输入信息函数，与后台chatwithvivo函数连接
  const sendMessage = async () => {
    if (message) {
      const data = {message: message};
      const jsonData = JSON.stringify(data);
      try {
        const response = await fetch('http:/10.0.2.2:5000/receive_data', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: jsonData,
        });
        type Message = {
              sender: string;
              text: string;
            };
        if (response.ok) {
          const responseData = await response.json();
          const processedData = responseData.response;

          setConversation([
            ...conversation,
            { sender: 'user', text: message },
            { sender: 'bot', text: processedData },
          ]);
          setMessage('');
        } else {
          console.error('Request failed with status:', response.status);
        }
      } catch (error) {
        console.error('Request failed with error:', error);
      }
    }
  };

  const [data, setData] = useState<YourData[]>([]);
  const fetchData = async () => {
    try {
      if (!isDataFetched) {
        const response = await fetch('http:/10.0.2.2:5000/random_clearfunny');
        const jsonData = await response.json();
        setData(jsonData);
        isDataFetched = true;
        console.log(isDataFetched);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
  fetchData();
  interface YourData {
    soup_surface: string; // 假设 column1 是一个字符串
    // 可以添加其他列...
  }
  return (
    <View style={styles.container}>
      {/* 汤面固定 */}
      <View style={styles.header}>
         {data.map((item, index) => (
           <Text style={styles.headerText} key={index}>
             {item.soup_surface}
           </Text>
         ))}
       </View>
      {/* 滚动屏 */}
      <ScrollView style={styles.conversation}>
        {/* 灰字提示部分 */}
        <View style={styles.welcomeContainer}>
          <Text style={styles.welcomeText}>欢迎进入海龟汤的游戏</Text>
          <Text style={styles.ruleText}>游戏中请注意以下规则：</Text>
          <Text style={styles.ruleText}>
            1. 根据汤面可以向主持人提问，尽量清楚描述问题，注意只会回答你是/否/与此无关
          </Text>
          <Text style={styles.ruleText}>
            2. 如果需要验证汤底，请点击下方的还原答案按钮。不过，你只有三次验证机会
          </Text>
          <Text style={styles.ruleText}>下面，你可以开始进行提问+猜测了！</Text>
          <Text style={styles.ruleText}>-------------------------</Text>
        </View>
        {/* 对话框 */}
        {conversation.map((item, index) => (
          <View
            key={index}
            style={
              item.sender === 'user' ? styles.userMessage : styles.botMessage
            }>
            <Text>{item.text}</Text>
          </View>
        ))}
      </ScrollView>
      {/* 还原答案和提示按钮 */}
      <View style={styles.answerButton}>
        <CustomButton title="还原答案" onPress={handleOpenModal} />
        <CustomButton title="提示" onPress={showAlert} />
      </View>
      {/* 底部输入框 */}
      <View style={styles.inputBox}>
        <TextInput
          style={styles.input}
          placeholder="请输入内容"
          value={message}
          onChangeText={text => setMessage(text)}
        />
        <CustomButton title="发送" onPress={sendMessage} />
      </View>
      {/* 汤面还原框 */}
      <Modal visible={showModal} animationType="slide" transparent={true}>
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <TextInput
              style={styles.input_guessstory}
              placeholder="请在此处还原你的汤面..."
              value={message2}
              textAlignVertical="top"
              multiline={true}
              onChangeText={text => setMessage2(text)}
            />
            <View style={styles.buttonbox}>
              <CustomButton title="发送" onPress={showresult} />
              <CustomButton title="返回" onPress={handleCloseModal} />
            </View>
          </View>
        </View>
      </Modal>
      {/* 成功框 */}
      <Modal visible={showModal2} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>成功</Text>
          <Image
            source={require('./bear.jpg')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal2} />
          <ConfettiCannon
            count={100}
            origin={{x: -10, y: 0}}
            explosionSpeed={300}
            fallSpeed={2000}
            colors={['#ff0000', '#00ff00', '#0000ff']}
          />
        </View>
      </Modal>
      {/* 失败框 */}
      <Modal visible={showModal3} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>失败</Text>
          <Image
            source={require('./bear2.gif')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal3} />
        </View>
      </Modal>
    </View>
  );
};
//---------------------------------------------------------------清汤-亲情
const Random_ClearLoveScreen = ({navigation}: Props) => {
  type Message = {
    sender: string;
    text: string;
  };
  const [conversation, setConversation] = useState<Message[]>([]);
  const [message, setMessage] = useState('');//存储用户对话框输入
  const [showPromptBox, setShowPromptBox] = useState(false);//“提示”框
  const [showModal, setShowModal] = useState(false);//还原答案框
  const [showModal2, setShowModal2] = useState(false);//成功框
  const [showModal3, setShowModal3] = useState(false);//失败框
  const [showResult, setResult] = useState(false);//结果框
  const [message2, setMessage2] = useState('');//存储用户还原答案输入
  const [errorCount, setErrorCount] = useState(0);
  // 控制还原答案框显示与否
  const handleOpenModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setShowModal(false);
  };
  // 控制成功答案框显示与否
  const handleOpenModal2 = () => {
    setShowModal2(true);
  };
  const handleCloseModal2 = () => {
    setShowModal2(false);
    navigation.navigate('Soup');
  };
  // 控制失败答案框显示与否
  const handleOpenModal3 = () => {
    setShowModal3(true);
  };
  const handleCloseModal3 = () => {
    setShowModal3(false);
    navigation.navigate('Soup');
  };
  // 提示框界面
  const showAlert = async () => {
    console.log('ok');
    try {
      const requestData = { message: '我需要获得提示' }; // 构造请求数据
      const jsonData = JSON.stringify(requestData);

      const response = await fetch('http://10.0.2.2:5000/receive_data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonData,
      });

      if (response.ok) {
        const responseData = await response.json();
        const processedData = responseData.response;

        // 将后端返回的结果显示在提示框中
        Alert.alert(
          '提示',
          `您获得的提示是：${processedData}`,
          [
            {
              text: '得到提示！<(￣︶￣)↗[GO!]',
              onPress: () => setShowPromptBox(false),
            },
          ],
          {
            cancelable: false,
          },
        );
      } else {
        console.error('Request failed with status:', response.status);
      }
    } catch (error) {
      console.error('Request failed with error:', error);
    }
  };
  //结果框界面
  const showresult = () => {
    const requestData = {
      message: message2,
    };
    let text2 = ' ';
    // 发送 POST 请求给后端
    fetch('http:/10.0.2.2:5000/guess', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData),
    })
      .then(response => response.json())
      .then(data => {
        // 处理后端返回的响应
        const response = JSON.stringify(data.response);
        // 更新前端的 text1
        text2 = response;
        const ifwin = data.response.substr(0, 4); // 只取前四个字
        setMessage2('');
        handleCloseModal();
        Alert.alert(
          `结果 您剩余的验证次数为 ${2 - errorCount}`,
          text2,
          [
            {
              text: '得到结果！<(￣︶￣)↗[GO!]',
              onPress: () => {
                if (ifwin === '回答正确') {
                  handleOpenModal2();
                } else if (ifwin === '回答错误') {
                  setResult(false);
                  if (errorCount >= 2) {
                    setErrorCount(0);
                    handleOpenModal3();
                  } else {
                    setErrorCount(errorCount + 1);
                  }
                }
              },
            },
          ],
          {
            cancelable: false,
          },
        );
      })
      .catch(error => {
        console.error('Error:', error);
      });
  };
  // 用户输入信息函数，与后台chatwithvivo函数连接
  const sendMessage = async () => {
    if (message) {
      const data = {message: message};
      const jsonData = JSON.stringify(data);
      try {
        const response = await fetch('http:/10.0.2.2:5000/receive_data', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: jsonData,
        });
        type Message = {
              sender: string;
              text: string;
            };
        if (response.ok) {
          const responseData = await response.json();
          const processedData = responseData.response;

          setConversation([
            ...conversation,
            { sender: 'user', text: message },
            { sender: 'bot', text: processedData },
          ]);
          setMessage('');
        } else {
          console.error('Request failed with status:', response.status);
        }
      } catch (error) {
        console.error('Request failed with error:', error);
      }
    }
  };

  const [data, setData] = useState<YourData[]>([]);
  const fetchData = async () => {
    try {
      if (!isDataFetched) {
        const response = await fetch('http:/10.0.2.2:5000/random_clearlove');
        const jsonData = await response.json();
        setData(jsonData);
        isDataFetched = true;
        console.log(isDataFetched);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
  fetchData();
  interface YourData {
    soup_surface: string; // 假设 column1 是一个字符串
    // 可以添加其他列...
  }
  return (
    <View style={styles.container}>
      {/* 汤面固定 */}
      <View style={styles.header}>
         {data.map((item, index) => (
           <Text style={styles.headerText} key={index}>
             {item.soup_surface}
           </Text>
         ))}
       </View>
      {/* 滚动屏 */}
      <ScrollView style={styles.conversation}>
        {/* 灰字提示部分 */}
        <View style={styles.welcomeContainer}>
          <Text style={styles.welcomeText}>欢迎进入海龟汤的游戏</Text>
          <Text style={styles.ruleText}>游戏中请注意以下规则：</Text>
          <Text style={styles.ruleText}>
            1. 根据汤面可以向主持人提问，尽量清楚描述问题，注意只会回答你是/否/与此无关
          </Text>
          <Text style={styles.ruleText}>
            2. 如果需要验证汤底，请点击下方的还原答案按钮。不过，你只有三次验证机会
          </Text>
          <Text style={styles.ruleText}>下面，你可以开始进行提问+猜测了！</Text>
          <Text style={styles.ruleText}>-------------------------</Text>
        </View>
        {/* 对话框 */}
        {conversation.map((item, index) => (
          <View
            key={index}
            style={
              item.sender === 'user' ? styles.userMessage : styles.botMessage
            }>
            <Text>{item.text}</Text>
          </View>
        ))}
      </ScrollView>
      {/* 还原答案和提示按钮 */}
      <View style={styles.answerButton}>
        <CustomButton title="还原答案" onPress={handleOpenModal} />
        <CustomButton title="提示" onPress={showAlert} />
      </View>
      {/* 底部输入框 */}
      <View style={styles.inputBox}>
        <TextInput
          style={styles.input}
          placeholder="请输入内容"
          value={message}
          onChangeText={text => setMessage(text)}
        />
        <CustomButton title="发送" onPress={sendMessage} />
      </View>
      {/* 汤面还原框 */}
      <Modal visible={showModal} animationType="slide" transparent={true}>
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <TextInput
              style={styles.input_guessstory}
              placeholder="请在此处还原你的汤面..."
              value={message2}
              textAlignVertical="top"
              multiline={true}
              onChangeText={text => setMessage2(text)}
            />
            <View style={styles.buttonbox}>
              <CustomButton title="发送" onPress={showresult} />
              <CustomButton title="返回" onPress={handleCloseModal} />
            </View>
          </View>
        </View>
      </Modal>
      {/* 成功框 */}
      <Modal visible={showModal2} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>成功</Text>
          <Image
            source={require('./bear.jpg')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal2} />
          <ConfettiCannon
            count={100}
            origin={{x: -10, y: 0}}
            explosionSpeed={300}
            fallSpeed={2000}
            colors={['#ff0000', '#00ff00', '#0000ff']}
          />
        </View>
      </Modal>
      {/* 失败框 */}
      <Modal visible={showModal3} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>失败</Text>
          <Image
            source={require('./bear2.gif')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal3} />
        </View>
      </Modal>
    </View>
  );
};
//-----------------------------------------------------------红汤-变态
const Random_RedMeTaScreen = ({navigation}: Props) => {
  type Message = {
    sender: string;
    text: string;
  };
  const [conversation, setConversation] = useState<Message[]>([]);
  const [message, setMessage] = useState('');//存储用户对话框输入
  const [showPromptBox, setShowPromptBox] = useState(false);//“提示”框
  const [showModal, setShowModal] = useState(false);//还原答案框
  const [showModal2, setShowModal2] = useState(false);//成功框
  const [showModal3, setShowModal3] = useState(false);//失败框
  const [showResult, setResult] = useState(false);//结果框
  const [message2, setMessage2] = useState('');//存储用户还原答案输入
  const [errorCount, setErrorCount] = useState(0);
  // 控制还原答案框显示与否
  const handleOpenModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setShowModal(false);
  };
  // 控制成功答案框显示与否
  const handleOpenModal2 = () => {
    setShowModal2(true);
  };
  const handleCloseModal2 = () => {
    setShowModal2(false);
    navigation.navigate('Soup');
  };
  // 控制失败答案框显示与否
  const handleOpenModal3 = () => {
    setShowModal3(true);
  };
  const handleCloseModal3 = () => {
    setShowModal3(false);
    navigation.navigate('Soup');
  };
  // 提示框界面
  const showAlert = async () => {
    console.log('ok');
    try {
      const requestData = { message: '我需要获得提示' }; // 构造请求数据
      const jsonData = JSON.stringify(requestData);

      const response = await fetch('http://10.0.2.2:5000/receive_data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonData,
      });

      if (response.ok) {
        const responseData = await response.json();
        const processedData = responseData.response;

        // 将后端返回的结果显示在提示框中
        Alert.alert(
          '提示',
          `您获得的提示是：${processedData}`,
          [
            {
              text: '得到提示！<(￣︶￣)↗[GO!]',
              onPress: () => setShowPromptBox(false),
            },
          ],
          {
            cancelable: false,
          },
        );
      } else {
        console.error('Request failed with status:', response.status);
      }
    } catch (error) {
      console.error('Request failed with error:', error);
    }
  };
  //结果框界面
  const showresult = () => {
    const requestData = {
      message: message2,
    };
    let text2 = ' ';
    // 发送 POST 请求给后端
    fetch('http:/10.0.2.2:5000/guess', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData),
    })
      .then(response => response.json())
      .then(data => {
        // 处理后端返回的响应
        const response = JSON.stringify(data.response);
        // 更新前端的 text1
        text2 = response;
        const ifwin = data.response.substr(0, 4); // 只取前四个字
        setMessage2('');
        handleCloseModal();
        Alert.alert(
          `结果 您剩余的验证次数为 ${2 - errorCount}`,
          text2,
          [
            {
              text: '得到结果！<(￣︶￣)↗[GO!]',
              onPress: () => {
                if (ifwin === '回答正确') {
                  handleOpenModal2();
                } else if (ifwin === '回答错误') {
                  setResult(false);
                  if (errorCount >= 2) {
                    setErrorCount(0);
                    handleOpenModal3();
                  } else {
                    setErrorCount(errorCount + 1);
                  }
                }
              },
            },
          ],
          {
            cancelable: false,
          },
        );
      })
      .catch(error => {
        console.error('Error:', error);
      });
  };
  // 用户输入信息函数，与后台chatwithvivo函数连接
  const sendMessage = async () => {
    if (message) {
      const data = {message: message};
      const jsonData = JSON.stringify(data);
      try {
        const response = await fetch('http:/10.0.2.2:5000/receive_data', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: jsonData,
        });
        type Message = {
              sender: string;
              text: string;
            };
        if (response.ok) {
          const responseData = await response.json();
          const processedData = responseData.response;

          setConversation([
            ...conversation,
            { sender: 'user', text: message },
            { sender: 'bot', text: processedData },
          ]);
          setMessage('');
        } else {
          console.error('Request failed with status:', response.status);
        }
      } catch (error) {
        console.error('Request failed with error:', error);
      }
    }
  };

  const [data, setData] = useState<YourData[]>([]);
  const fetchData = async () => {
    try {
      if (!isDataFetched) {
        const response = await fetch('http:/10.0.2.2:5000/random_redmeta');
        const jsonData = await response.json();
        setData(jsonData);
        isDataFetched = true;
        console.log(isDataFetched);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
  fetchData();
  interface YourData {
    soup_surface: string; // 假设 column1 是一个字符串
    // 可以添加其他列...
  }
  return (
    <View style={styles.container}>
      {/* 汤面固定 */}
      <View style={styles.header}>
         {data.map((item, index) => (
           <Text style={styles.headerText} key={index}>
             {item.soup_surface}
           </Text>
         ))}
       </View>
      {/* 滚动屏 */}
      <ScrollView style={styles.conversation}>
        {/* 灰字提示部分 */}
        <View style={styles.welcomeContainer}>
          <Text style={styles.welcomeText}>欢迎进入海龟汤的游戏</Text>
          <Text style={styles.ruleText}>游戏中请注意以下规则：</Text>
          <Text style={styles.ruleText}>
            1. 根据汤面可以向主持人提问，尽量清楚描述问题，注意只会回答你是/否/与此无关
          </Text>
          <Text style={styles.ruleText}>
            2. 如果需要验证汤底，请点击下方的还原答案按钮。不过，你只有三次验证机会
          </Text>
          <Text style={styles.ruleText}>下面，你可以开始进行提问+猜测了！</Text>
          <Text style={styles.ruleText}>-------------------------</Text>
        </View>
        {/* 对话框 */}
        {conversation.map((item, index) => (
          <View
            key={index}
            style={
              item.sender === 'user' ? styles.userMessage : styles.botMessage
            }>
            <Text>{item.text}</Text>
          </View>
        ))}
      </ScrollView>
      {/* 还原答案和提示按钮 */}
      <View style={styles.answerButton}>
        <CustomButton title="还原答案" onPress={handleOpenModal} />
        <CustomButton title="提示" onPress={showAlert} />
      </View>
      {/* 底部输入框 */}
      <View style={styles.inputBox}>
        <TextInput
          style={styles.input}
          placeholder="请输入内容"
          value={message}
          onChangeText={text => setMessage(text)}
        />
        <CustomButton title="发送" onPress={sendMessage} />
      </View>
      {/* 汤面还原框 */}
      <Modal visible={showModal} animationType="slide" transparent={true}>
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <TextInput
              style={styles.input_guessstory}
              placeholder="请在此处还原你的汤面..."
              value={message2}
              textAlignVertical="top"
              multiline={true}
              onChangeText={text => setMessage2(text)}
            />
            <View style={styles.buttonbox}>
              <CustomButton title="发送" onPress={showresult} />
              <CustomButton title="返回" onPress={handleCloseModal} />
            </View>
          </View>
        </View>
      </Modal>
      {/* 成功框 */}
      <Modal visible={showModal2} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>成功</Text>
          <Image
            source={require('./bear.jpg')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal2} />
          <ConfettiCannon
            count={100}
            origin={{x: -10, y: 0}}
            explosionSpeed={300}
            fallSpeed={2000}
            colors={['#ff0000', '#00ff00', '#0000ff']}
          />
        </View>
      </Modal>
      {/* 失败框 */}
      <Modal visible={showModal3} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>失败</Text>
          <Image
            source={require('./bear2.gif')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal3} />
        </View>
      </Modal>
    </View>
  );
};

//-----------------------------------红汤-奇幻
const Random_RedLoveScreen = ({navigation}: Props) => {
  type Message = {
    sender: string;
    text: string;
  };
  const [conversation, setConversation] = useState<Message[]>([]);
  const [message, setMessage] = useState('');//存储用户对话框输入
  const [showPromptBox, setShowPromptBox] = useState(false);//“提示”框
  const [showModal, setShowModal] = useState(false);//还原答案框
  const [showModal2, setShowModal2] = useState(false);//成功框
  const [showModal3, setShowModal3] = useState(false);//失败框
  const [showResult, setResult] = useState(false);//结果框
  const [message2, setMessage2] = useState('');//存储用户还原答案输入
  const [errorCount, setErrorCount] = useState(0);
  // 控制还原答案框显示与否
  const handleOpenModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setShowModal(false);
  };
  // 控制成功答案框显示与否
  const handleOpenModal2 = () => {
    setShowModal2(true);
  };
  const handleCloseModal2 = () => {
    setShowModal2(false);
    navigation.navigate('Soup');
  };
  // 控制失败答案框显示与否
  const handleOpenModal3 = () => {
    setShowModal3(true);
  };
  const handleCloseModal3 = () => {
    setShowModal3(false);
    navigation.navigate('Soup');
  };
  // 提示框界面
  const showAlert = async () => {
    console.log('ok');
    try {
      const requestData = { message: '我需要获得提示' }; // 构造请求数据
      const jsonData = JSON.stringify(requestData);

      const response = await fetch('http://10.0.2.2:5000/receive_data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonData,
      });

      if (response.ok) {
        const responseData = await response.json();
        const processedData = responseData.response;

        // 将后端返回的结果显示在提示框中
        Alert.alert(
          '提示',
          `您获得的提示是：${processedData}`,
          [
            {
              text: '得到提示！<(￣︶￣)↗[GO!]',
              onPress: () => setShowPromptBox(false),
            },
          ],
          {
            cancelable: false,
          },
        );
      } else {
        console.error('Request failed with status:', response.status);
      }
    } catch (error) {
      console.error('Request failed with error:', error);
    }
  };
  //结果框界面
  const showresult = () => {
    const requestData = {
      message: message2,
    };
    let text2 = ' ';
    // 发送 POST 请求给后端
    fetch('http:/10.0.2.2:5000/guess', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData),
    })
      .then(response => response.json())
      .then(data => {
        // 处理后端返回的响应
        const response = JSON.stringify(data.response);
        // 更新前端的 text1
        text2 = response;
        const ifwin = data.response.substr(0, 4); // 只取前四个字
        setMessage2('');
        handleCloseModal();
        Alert.alert(
          `结果 您剩余的验证次数为 ${2 - errorCount}`,
          text2,
          [
            {
              text: '得到结果！<(￣︶￣)↗[GO!]',
              onPress: () => {
                if (ifwin === '回答正确') {
                  handleOpenModal2();
                } else if (ifwin === '回答错误') {
                  setResult(false);
                  if (errorCount >= 2) {
                    setErrorCount(0);
                    handleOpenModal3();
                  } else {
                    setErrorCount(errorCount + 1);
                  }
                }
              },
            },
          ],
          {
            cancelable: false,
          },
        );
      })
      .catch(error => {
        console.error('Error:', error);
      });
  };
  // 用户输入信息函数，与后台chatwithvivo函数连接
  const sendMessage = async () => {
    if (message) {
      const data = {message: message};
      const jsonData = JSON.stringify(data);
      try {
        const response = await fetch('http:/10.0.2.2:5000/receive_data', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: jsonData,
        });
        type Message = {
              sender: string;
              text: string;
            };
        if (response.ok) {
          const responseData = await response.json();
          const processedData = responseData.response;

          setConversation([
            ...conversation,
            { sender: 'user', text: message },
            { sender: 'bot', text: processedData },
          ]);
          setMessage('');
        } else {
          console.error('Request failed with status:', response.status);
        }
      } catch (error) {
        console.error('Request failed with error:', error);
      }
    }
  };

  const [data, setData] = useState<YourData[]>([]);
  const fetchData = async () => {
    try {
      if (!isDataFetched) {
        const response = await fetch('http:/10.0.2.2:5000/random_redlove');
        const jsonData = await response.json();
        setData(jsonData);
        isDataFetched = true;
        console.log(isDataFetched);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
  fetchData();
  interface YourData {
    soup_surface: string; // 假设 column1 是一个字符串
    // 可以添加其他列...
  }
  return (
    <View style={styles.container}>
      {/* 汤面固定 */}
      <View style={styles.header}>
         {data.map((item, index) => (
           <Text style={styles.headerText} key={index}>
             {item.soup_surface}
           </Text>
         ))}
       </View>
      {/* 滚动屏 */}
      <ScrollView style={styles.conversation}>
        {/* 灰字提示部分 */}
        <View style={styles.welcomeContainer}>
          <Text style={styles.welcomeText}>欢迎进入海龟汤的游戏</Text>
          <Text style={styles.ruleText}>游戏中请注意以下规则：</Text>
          <Text style={styles.ruleText}>
            1. 根据汤面可以向主持人提问，尽量清楚描述问题，注意只会回答你是/否/与此无关
          </Text>
          <Text style={styles.ruleText}>
            2. 如果需要验证汤底，请点击下方的还原答案按钮。不过，你只有三次验证机会
          </Text>
          <Text style={styles.ruleText}>下面，你可以开始进行提问+猜测了！</Text>
          <Text style={styles.ruleText}>-------------------------</Text>
        </View>
        {/* 对话框 */}
        {conversation.map((item, index) => (
          <View
            key={index}
            style={
              item.sender === 'user' ? styles.userMessage : styles.botMessage
            }>
            <Text>{item.text}</Text>
          </View>
        ))}
      </ScrollView>
      {/* 还原答案和提示按钮 */}
      <View style={styles.answerButton}>
        <CustomButton title="还原答案" onPress={handleOpenModal} />
        <CustomButton title="提示" onPress={showAlert} />
      </View>
      {/* 底部输入框 */}
      <View style={styles.inputBox}>
        <TextInput
          style={styles.input}
          placeholder="请输入内容"
          value={message}
          onChangeText={text => setMessage(text)}
        />
        <CustomButton title="发送" onPress={sendMessage} />
      </View>
      {/* 汤面还原框 */}
      <Modal visible={showModal} animationType="slide" transparent={true}>
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <TextInput
              style={styles.input_guessstory}
              placeholder="请在此处还原你的汤面..."
              value={message2}
              textAlignVertical="top"
              multiline={true}
              onChangeText={text => setMessage2(text)}
            />
            <View style={styles.buttonbox}>
              <CustomButton title="发送" onPress={showresult} />
              <CustomButton title="返回" onPress={handleCloseModal} />
            </View>
          </View>
        </View>
      </Modal>
      {/* 成功框 */}
      <Modal visible={showModal2} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>成功</Text>
          <Image
            source={require('./bear.jpg')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal2} />
          <ConfettiCannon
            count={100}
            origin={{x: -10, y: 0}}
            explosionSpeed={300}
            fallSpeed={2000}
            colors={['#ff0000', '#00ff00', '#0000ff']}
          />
        </View>
      </Modal>
      {/* 失败框 */}
      <Modal visible={showModal3} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>失败</Text>
          <Image
            source={require('./bear2.gif')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal3} />
        </View>
      </Modal>
    </View>
  );
};
//------------------------------------------红汤-搞笑
const Random_RedFunnyScreen = ({navigation}: Props) => {
  type Message = {
    sender: string;
    text: string;
  };
  const [conversation, setConversation] = useState<Message[]>([]);
  const [message, setMessage] = useState('');//存储用户对话框输入
  const [showPromptBox, setShowPromptBox] = useState(false);//“提示”框
  const [showModal, setShowModal] = useState(false);//还原答案框
  const [showModal2, setShowModal2] = useState(false);//成功框
  const [showModal3, setShowModal3] = useState(false);//失败框
  const [showResult, setResult] = useState(false);//结果框
  const [message2, setMessage2] = useState('');//存储用户还原答案输入
  const [errorCount, setErrorCount] = useState(0);
  // 控制还原答案框显示与否
  const handleOpenModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setShowModal(false);
  };
  // 控制成功答案框显示与否
  const handleOpenModal2 = () => {
    setShowModal2(true);
  };
  const handleCloseModal2 = () => {
    setShowModal2(false);
    navigation.navigate('Soup');
  };
  // 控制失败答案框显示与否
  const handleOpenModal3 = () => {
    setShowModal3(true);
  };
  const handleCloseModal3 = () => {
    setShowModal3(false);
    navigation.navigate('Soup');
  };
  // 提示框界面
  const showAlert = async () => {
    console.log('ok');
    try {
      const requestData = { message: '我需要获得提示' }; // 构造请求数据
      const jsonData = JSON.stringify(requestData);

      const response = await fetch('http://10.0.2.2:5000/receive_data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonData,
      });

      if (response.ok) {
        const responseData = await response.json();
        const processedData = responseData.response;

        // 将后端返回的结果显示在提示框中
        Alert.alert(
          '提示',
          `您获得的提示是：${processedData}`,
          [
            {
              text: '得到提示！<(￣︶￣)↗[GO!]',
              onPress: () => setShowPromptBox(false),
            },
          ],
          {
            cancelable: false,
          },
        );
      } else {
        console.error('Request failed with status:', response.status);
      }
    } catch (error) {
      console.error('Request failed with error:', error);
    }
  };
  //结果框界面
  const showresult = () => {
    const requestData = {
      message: message2,
    };
    let text2 = ' ';
    // 发送 POST 请求给后端
    fetch('http:/10.0.2.2:5000/guess', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData),
    })
      .then(response => response.json())
      .then(data => {
        // 处理后端返回的响应
        const response = JSON.stringify(data.response);
        // 更新前端的 text1
        text2 = response;
        const ifwin = data.response.substr(0, 4); // 只取前四个字
        setMessage2('');
        handleCloseModal();
        Alert.alert(
          `结果 您剩余的验证次数为 ${2 - errorCount}`,
          text2,
          [
            {
              text: '得到结果！<(￣︶￣)↗[GO!]',
              onPress: () => {
                if (ifwin === '回答正确') {
                  handleOpenModal2();
                } else if (ifwin === '回答错误') {
                  setResult(false);
                  if (errorCount >= 2) {
                    setErrorCount(0);
                    handleOpenModal3();
                  } else {
                    setErrorCount(errorCount + 1);
                  }
                }
              },
            },
          ],
          {
            cancelable: false,
          },
        );
      })
      .catch(error => {
        console.error('Error:', error);
      });
  };
  // 用户输入信息函数，与后台chatwithvivo函数连接
  const sendMessage = async () => {
    if (message) {
      const data = {message: message};
      const jsonData = JSON.stringify(data);
      try {
        const response = await fetch('http:/10.0.2.2:5000/receive_data', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: jsonData,
        });
        type Message = {
              sender: string;
              text: string;
            };
        if (response.ok) {
          const responseData = await response.json();
          const processedData = responseData.response;

          setConversation([
            ...conversation,
            { sender: 'user', text: message },
            { sender: 'bot', text: processedData },
          ]);
          setMessage('');
        } else {
          console.error('Request failed with status:', response.status);
        }
      } catch (error) {
        console.error('Request failed with error:', error);
      }
    }
  };

  const [data, setData] = useState<YourData[]>([]);
  const fetchData = async () => {
    try {
      if (!isDataFetched) {
        const response = await fetch('http:/10.0.2.2:5000/random_redfunny');
        const jsonData = await response.json();
        setData(jsonData);
        isDataFetched = true;
        console.log(isDataFetched);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
  fetchData();
  interface YourData {
    soup_surface: string; // 假设 column1 是一个字符串
    // 可以添加其他列...
  }
  return (
    <View style={styles.container}>
      {/* 汤面固定 */}
      <View style={styles.header}>
         {data.map((item, index) => (
           <Text style={styles.headerText} key={index}>
             {item.soup_surface}
           </Text>
         ))}
       </View>
      {/* 滚动屏 */}
      <ScrollView style={styles.conversation}>
        {/* 灰字提示部分 */}
        <View style={styles.welcomeContainer}>
          <Text style={styles.welcomeText}>欢迎进入海龟汤的游戏</Text>
          <Text style={styles.ruleText}>游戏中请注意以下规则：</Text>
          <Text style={styles.ruleText}>
            1. 根据汤面可以向主持人提问，尽量清楚描述问题，注意只会回答你是/否/与此无关
          </Text>
          <Text style={styles.ruleText}>
            2. 如果需要验证汤底，请点击下方的还原答案按钮。不过，你只有三次验证机会
          </Text>
          <Text style={styles.ruleText}>下面，你可以开始进行提问+猜测了！</Text>
          <Text style={styles.ruleText}>-------------------------</Text>
        </View>
        {/* 对话框 */}
        {conversation.map((item, index) => (
          <View
            key={index}
            style={
              item.sender === 'user' ? styles.userMessage : styles.botMessage
            }>
            <Text>{item.text}</Text>
          </View>
        ))}
      </ScrollView>
      {/* 还原答案和提示按钮 */}
      <View style={styles.answerButton}>
        <CustomButton title="还原答案" onPress={handleOpenModal} />
        <CustomButton title="提示" onPress={showAlert} />
      </View>
      {/* 底部输入框 */}
      <View style={styles.inputBox}>
        <TextInput
          style={styles.input}
          placeholder="请输入内容"
          value={message}
          onChangeText={text => setMessage(text)}
        />
        <CustomButton title="发送" onPress={sendMessage} />
      </View>
      {/* 汤面还原框 */}
      <Modal visible={showModal} animationType="slide" transparent={true}>
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <TextInput
              style={styles.input_guessstory}
              placeholder="请在此处还原你的汤面..."
              value={message2}
              textAlignVertical="top"
              multiline={true}
              onChangeText={text => setMessage2(text)}
            />
            <View style={styles.buttonbox}>
              <CustomButton title="发送" onPress={showresult} />
              <CustomButton title="返回" onPress={handleCloseModal} />
            </View>
          </View>
        </View>
      </Modal>
      {/* 成功框 */}
      <Modal visible={showModal2} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>成功</Text>
          <Image
            source={require('./bear.jpg')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal2} />
          <ConfettiCannon
            count={100}
            origin={{x: -10, y: 0}}
            explosionSpeed={300}
            fallSpeed={2000}
            colors={['#ff0000', '#00ff00', '#0000ff']}
          />
        </View>
      </Modal>
      {/* 失败框 */}
      <Modal visible={showModal3} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>失败</Text>
          <Image
            source={require('./bear2.gif')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal3} />
        </View>
      </Modal>
    </View>
  );
};
//------------------------------------------红汤-亲情
const Random_RedFantasyScreen = ({navigation}: Props) => {
  type Message = {
    sender: string;
    text: string;
  };
  const [conversation, setConversation] = useState<Message[]>([]);
  const [message, setMessage] = useState('');//存储用户对话框输入
  const [showPromptBox, setShowPromptBox] = useState(false);//“提示”框
  const [showModal, setShowModal] = useState(false);//还原答案框
  const [showModal2, setShowModal2] = useState(false);//成功框
  const [showModal3, setShowModal3] = useState(false);//失败框
  const [showResult, setResult] = useState(false);//结果框
  const [message2, setMessage2] = useState('');//存储用户还原答案输入
  const [errorCount, setErrorCount] = useState(0);
  // 控制还原答案框显示与否
  const handleOpenModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setShowModal(false);
  };
  // 控制成功答案框显示与否
  const handleOpenModal2 = () => {
    setShowModal2(true);
  };
  const handleCloseModal2 = () => {
    setShowModal2(false);
    navigation.navigate('Soup');
  };
  // 控制失败答案框显示与否
  const handleOpenModal3 = () => {
    setShowModal3(true);
  };
  const handleCloseModal3 = () => {
    setShowModal3(false);
    navigation.navigate('Soup');
  };
  // 提示框界面
  const showAlert = async () => {
    console.log('ok');
    try {
      const requestData = { message: '我需要获得提示' }; // 构造请求数据
      const jsonData = JSON.stringify(requestData);

      const response = await fetch('http://10.0.2.2:5000/receive_data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonData,
      });

      if (response.ok) {
        const responseData = await response.json();
        const processedData = responseData.response;

        // 将后端返回的结果显示在提示框中
        Alert.alert(
          '提示',
          `您获得的提示是：${processedData}`,
          [
            {
              text: '得到提示！<(￣︶￣)↗[GO!]',
              onPress: () => setShowPromptBox(false),
            },
          ],
          {
            cancelable: false,
          },
        );
      } else {
        console.error('Request failed with status:', response.status);
      }
    } catch (error) {
      console.error('Request failed with error:', error);
    }
  };
  //结果框界面
  const showresult = () => {
    const requestData = {
      message: message2,
    };
    let text2 = ' ';
    // 发送 POST 请求给后端
    fetch('http:/10.0.2.2:5000/guess', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData),
    })
      .then(response => response.json())
      .then(data => {
        // 处理后端返回的响应
        const response = JSON.stringify(data.response);
        // 更新前端的 text1
        text2 = response;
        const ifwin = data.response.substr(0, 4); // 只取前四个字
        setMessage2('');
        handleCloseModal();
        Alert.alert(
          `结果 您剩余的验证次数为 ${2 - errorCount}`,
          text2,
          [
            {
              text: '得到结果！<(￣︶￣)↗[GO!]',
              onPress: () => {
                if (ifwin === '回答正确') {
                  handleOpenModal2();
                } else if (ifwin === '回答错误') {
                  setResult(false);
                  if (errorCount >= 2) {
                    setErrorCount(0);
                    handleOpenModal3();
                  } else {
                    setErrorCount(errorCount + 1);
                  }
                }
              },
            },
          ],
          {
            cancelable: false,
          },
        );
      })
      .catch(error => {
        console.error('Error:', error);
      });
  };
  // 用户输入信息函数，与后台chatwithvivo函数连接
  const sendMessage = async () => {
    if (message) {
      const data = {message: message};
      const jsonData = JSON.stringify(data);
      try {
        const response = await fetch('http:/10.0.2.2:5000/receive_data', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: jsonData,
        });
        type Message = {
              sender: string;
              text: string;
            };
        if (response.ok) {
          const responseData = await response.json();
          const processedData = responseData.response;

          setConversation([
            ...conversation,
            { sender: 'user', text: message },
            { sender: 'bot', text: processedData },
          ]);
          setMessage('');
        } else {
          console.error('Request failed with status:', response.status);
        }
      } catch (error) {
        console.error('Request failed with error:', error);
      }
    }
  };

  const [data, setData] = useState<YourData[]>([]);
  const fetchData = async () => {
    try {
      if (!isDataFetched) {
        const response = await fetch('http:/10.0.2.2:5000/random_redfantasy');
        const jsonData = await response.json();
        setData(jsonData);
        isDataFetched = true;
        console.log(isDataFetched);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };
  fetchData();
  interface YourData {
    soup_surface: string; // 假设 column1 是一个字符串
    // 可以添加其他列...
  }
  return (
    <View style={styles.container}>
      {/* 汤面固定 */}
      <View style={styles.header}>
         {data.map((item, index) => (
           <Text style={styles.headerText} key={index}>
             {item.soup_surface}
           </Text>
         ))}
       </View>
      {/* 滚动屏 */}
      <ScrollView style={styles.conversation}>
        {/* 灰字提示部分 */}
        <View style={styles.welcomeContainer}>
          <Text style={styles.welcomeText}>欢迎进入海龟汤的游戏</Text>
          <Text style={styles.ruleText}>游戏中请注意以下规则：</Text>
          <Text style={styles.ruleText}>
            1. 根据汤面可以向主持人提问，尽量清楚描述问题，注意只会回答你是/否/与此无关
          </Text>
          <Text style={styles.ruleText}>
            2. 如果需要验证汤底，请点击下方的还原答案按钮。不过，你只有三次验证机会
          </Text>
          <Text style={styles.ruleText}>下面，你可以开始进行提问+猜测了！</Text>
          <Text style={styles.ruleText}>-------------------------</Text>
        </View>
        {/* 对话框 */}
        {conversation.map((item, index) => (
          <View
            key={index}
            style={
              item.sender === 'user' ? styles.userMessage : styles.botMessage
            }>
            <Text>{item.text}</Text>
          </View>
        ))}
      </ScrollView>
      {/* 还原答案和提示按钮 */}
      <View style={styles.answerButton}>
        <CustomButton title="还原答案" onPress={handleOpenModal} />
        <CustomButton title="提示" onPress={showAlert} />
      </View>
      {/* 底部输入框 */}
      <View style={styles.inputBox}>
        <TextInput
          style={styles.input}
          placeholder="请输入内容"
          value={message}
          onChangeText={text => setMessage(text)}
        />
        <CustomButton title="发送" onPress={sendMessage} />
      </View>
      {/* 汤面还原框 */}
      <Modal visible={showModal} animationType="slide" transparent={true}>
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <TextInput
              style={styles.input_guessstory}
              placeholder="请在此处还原你的汤面..."
              value={message2}
              textAlignVertical="top"
              multiline={true}
              onChangeText={text => setMessage2(text)}
            />
            <View style={styles.buttonbox}>
              <CustomButton title="发送" onPress={showresult} />
              <CustomButton title="返回" onPress={handleCloseModal} />
            </View>
          </View>
        </View>
      </Modal>
      {/* 成功框 */}
      <Modal visible={showModal2} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>成功</Text>
          <Image
            source={require('./bear.jpg')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal2} />
          <ConfettiCannon
            count={100}
            origin={{x: -10, y: 0}}
            explosionSpeed={300}
            fallSpeed={2000}
            colors={['#ff0000', '#00ff00', '#0000ff']}
          />
        </View>
      </Modal>
      {/* 失败框 */}
      <Modal visible={showModal3} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>失败</Text>
          <Image
            source={require('./bear2.gif')}
            style={{width: 400, height: 400}}
          />
          <CustomButton title="back" onPress={handleCloseModal3} />
        </View>
      </Modal>
    </View>
  );
};


const ClearSoupScreen = ({ navigation }:Props) => {
  const [showModal, setShowModal] = useState(false);
  const [selectedType, setSelectedType] = useState('');

  const showConfirmation = (type: string) => {
    setSelectedType(type);
    setShowModal(true); // 显示弹窗
    isDataFetched=false;
  };

  const handleConfirmation = (choice: string) => {
    setShowModal(false);
    if (choice === 'yes') {
      if (selectedType === '奇幻') {
        navigation.navigate('Random_ClearFantasy');
      } else if (selectedType === '搞笑') {
        navigation.navigate('Random_ClearFunny');
      } else if (selectedType === '亲情') {
        navigation.navigate('Random_ClearLove');
      }
    } else {
      if (selectedType === '奇幻') {
        navigation.navigate('ClearFantasy_Tangmian');
      } else if (selectedType === '搞笑') {
        navigation.navigate('ClearFunny_Tangmian');
      } else if (selectedType === '亲情') {
        navigation.navigate('ClearLove_Tangmian');
      }
    }
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={[styles.button, styles.clearButton, styles.buttonWithMargin]}
        onPress={() => showConfirmation('奇幻')}
      >
        <Text style={styles.buttonText1}>奇幻</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.button, styles.clearButton, styles.buttonWithMargin]}
        onPress={() => showConfirmation('搞笑')}
      >
        <Text style={styles.buttonText1}>搞笑</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.button, styles.clearButton, styles.buttonWithMargin]}
        onPress={() => showConfirmation('亲情')}
      >
        <Text style={styles.buttonText1}>亲情</Text>
      </TouchableOpacity>

      {showModal && (
        <Modal transparent={true} animationType="slide">
          <View style={styles.modal}>
            <Text style={[styles.modalText, styles.boldText]}>是否随机选择汤底？</Text>
            <Text style={[styles.modalText, styles.boldText]}>当前选择: {selectedType}</Text>
            <View style={styles.modalButtons}>
              <TouchableOpacity
                style={styles.modalButton}
                onPress={() => handleConfirmation('yes')}
              >
                <Text style={styles.modalButtonText}>是</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.modalButton}
                onPress={() => handleConfirmation('no')}
              >
                <Text style={styles.modalButtonText}>否</Text>
              </TouchableOpacity>
            </View>
          </View>
        </Modal>
      )}
    </View>
  );
};


//------------------------------------------用户选择-清汤-搞笑
interface Item {
  soup_surface: string;
}
const SERVER_URL = 'http://10.0.2.2:5000'; // 确保这是你的Flask服务器地址
const ClearFunny_TangmianScreen = ({navigation}:Props) => {
  const [data, setData] = useState<Item[]>([]);
  useEffect(() => {
    fetchDataFromServer();
  }, []);

  const fetchDataFromServer = async () => {
    try {
      const response = await fetch(`${SERVER_URL}/clearfunny_tangmian`);
      const result = await response.json();
      setData(result);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  return (
    <View style={screenstyles.container}>
      <ScrollView contentContainerStyle={screenstyles.scrollViewContainer}>
        <View style={screenstyles.listContainer}>
          {data.map((item, index) => (
            <TouchableOpacity
              key={index}
              style={screenstyles.box}
              onPress={() => navigation.navigate('ClearFunny', { soup_surface: item.soup_surface })}
            >
              <View style={screenstyles.border}>
                <Text style={screenstyles.text}>{item.soup_surface}</Text>
              </View>
            </TouchableOpacity>
          ))}
        </View>
      </ScrollView>
      <Button title="重新获取数据" onPress={fetchDataFromServer} />
    </View>
  );
};


const screenstyles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  scrollViewContainer: {
    alignItems: 'center',
  },
  listContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  box: {
    width: '98%', // Two boxes per row
    height: 100,
    marginBottom: 15,
  },
  border: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#ADD8E6',
    backgroundColor: '#ADD8E6',
    borderRadius: 8,
  },
  text: {
    fontSize: 16,
    color: '#FFFFFF',
    textAlign: 'center',
  },
});

// export default ClearFunny_TangmianScreen;

type ClearFunnyScreenRouteProp = RouteProp<{
  ClearFunnyScreen: { soup_surface: string }; // 在这里定义你的路由参数
}, 'ClearFunnyScreen'>;

interface ConversationItem {
  sender: string;
  text: string;
}

interface DataItem {
  soup_surface: string;
}
const ClearFunnyScreen = ({ route, navigation }:{ route: ClearFunnyScreenRouteProp, navigation: any }) => {
  const { soup_surface } = route.params;
  const [conversation, setConversation] = useState<ConversationItem[]>([]);
  const [message, setMessage] = useState('');
  const [showPromptBox, setShowPromptBox] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [showModal2, setShowModal2] = useState(false);
  const [showModal3, setShowModal3] = useState(false);
  const [showResult, setResult] = useState(false);
  const [message2, setMessage2] = useState('');
  const [errorCount, setErrorCount] = useState(0);

  const [data, setData] = useState<DataItem[]>([]);
  const [isDataFetched, setIsDataFetched] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      try {
        if (!isDataFetched) {
          const response = await fetch(`${SERVER_URL}/clearfunny`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ soup_surface }),
          });
          if (!response.ok) {
            throw new Error('Failed to fetch data');
          }
          const jsonData = await response.json();
          setData(jsonData);
          setIsDataFetched(true);
          console.log('Data fetched:', jsonData);
        }
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, [isDataFetched, soup_surface]); // Ensure useEffect runs when isDataFetched or soup_surface changes

  interface YourData {
    soup_surface: string;
    // Add other fields as needed
  }


  const handleOpenModal = () => {
    setShowModal(true);
  };
  const handleCloseModal = () => {
    setShowModal(false);
  };
  const handleOpenModal2 = () => {
    setShowModal2(true);
  };
  const handleCloseModal2 = () => {
    setShowModal2(false);
    navigation.navigate('Soup');
  };
  const handleOpenModal3 = () => {
    setShowModal3(true);
  };
  const handleCloseModal3 = () => {
    setShowModal3(false);
    navigation.navigate('Soup');
  };

  const showAlert = async () => {
    console.log('ok');
    try {
      const requestData = { message: '我需要获得提示' };
      const jsonData = JSON.stringify(requestData);

      const response = await fetch('http://10.0.2.2:5000/receive_data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonData,
      });

      if (response.ok) {
        const responseData = await response.json();
        const processedData = responseData.response;

        Alert.alert(
          '提示',
          `您获得的提示是：${processedData}`,
          [
            {
              text: '得到提示！<(￣︶￣)↗[GO!]',
              onPress: () => setShowPromptBox(false),
            },
          ],
          {
            cancelable: false,
          },
        );
      } else {
        console.error('Request failed with status:', response.status);
      }
    } catch (error) {
      console.error('Request failed with error:', error);
    }
  };

  const showresult = () => {
    const requestData = { message: message2 };
    let text2 = ' ';
    fetch('http:/10.0.2.2:5000/guess', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestData),
    })
      .then(response => response.json())
      .then(data => {
        const response = JSON.stringify(data.response);
        text2 = response;
        const ifwin = data.response.substr(0, 4);
        setMessage2('');
        handleCloseModal();
        Alert.alert(
          `结果 您剩余的验证次数为 ${2 - errorCount}`,
          text2,
          [
            {
              text: '得到结果！<(￣︶￣)↗[GO!]',
              onPress: () => {
                if (ifwin === '回答正确') {
                  handleOpenModal2();
                } else if (ifwin === '回答错误') {
                  setResult(false);
                  if (errorCount >= 2) {
                    setErrorCount(0);
                    handleOpenModal3();
                  } else {
                    setErrorCount(errorCount + 1);
                  }
                }
              },
            },
          ],
          {
            cancelable: false,
          },
        );
      })
      .catch(error => {
        console.error('Error:', error);
      });
  };
  
  const sendMessage = async () => {
    if (message) {
      const data = { message };
      const jsonData = JSON.stringify(data);
      const [conversation, setConversation] = useState<{ sender: string; text: string }[]>([]);
      try {
        const response = await fetch('http:/10.0.2.2:5000/receive_data', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: jsonData,
        });
        if (response.ok) {
          const responseData = await response.json();
          const processedData = responseData.response;
          setConversation([
            ...conversation,
            { sender: 'user', text: message },
            { sender: 'bot', text: processedData },
          ]);
          setMessage('');
        } else {
          console.error('Request failed with status:', response.status);
        }
      } catch (error) {
        console.error('Request failed with error:', error);
      }
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        {data.map((item, index) => (
          <Text style={styles.headerText} key={index}>
            {item.soup_surface}
          </Text>
        ))}
      </View>
      <ScrollView style={styles.conversation}>
        <View style={styles.welcomeContainer}>
          <Text style={styles.welcomeText}>欢迎进入海龟汤的游戏</Text>
          <Text style={styles.ruleText}>游戏中请注意以下规则：</Text>
          <Text style={styles.ruleText}>
            1. 根据汤面可以向主持人提问，尽量清楚描述问题，注意只会回答你是/否/与此无关
          </Text>
          <Text style={styles.ruleText}>
            2. 如果需要验证汤底，请点击下方的还原答案按钮。不过，你只有三次验证机会
          </Text>
          <Text style={styles.ruleText}>下面，你可以开始进行提问+猜测了！</Text>
          <Text style={styles.ruleText}>-------------------------</Text>
        </View>
        {conversation.map((item, index) => (
          <View key={index} style={item.sender === 'user' ? styles.userMessage : styles.botMessage}>
            <Text>{item.text}</Text>
          </View>
        ))}
      </ScrollView>
      <View style={styles.answerButton}>
        <CustomButton title="还原答案" onPress={handleOpenModal} />
        <CustomButton title="提示" onPress={showAlert} />
      </View>
      <View style={styles.inputBox}>
        <TextInput
          style={styles.input}
          placeholder="请输入内容"
          value={message}
          onChangeText={text => setMessage(text)}
        />
        <CustomButton title="发送" onPress={sendMessage} />
      </View>
      <Modal visible={showModal} animationType="slide" transparent={true}>
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <TextInput
              style={styles.input_guessstory}
              placeholder="请在此处还原你的汤面..."
              value={message2}
              textAlignVertical="top"
              multiline={true}
              onChangeText={text => setMessage2(text)}
            />
            <View style={styles.buttonbox}>
              <CustomButton title="发送" onPress={showresult} />
              <CustomButton title="返回" onPress={handleCloseModal} />
            </View>
          </View>
        </View>
      </Modal>
      <Modal visible={showModal2} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>成功</Text>
          <Image
            source={require('./bear.jpg')}
            style={{ width: 400, height: 400 }}
          />
          <CustomButton title="back" onPress={handleCloseModal2} />
          <ConfettiCannon
            count={100}
            origin={{ x: -10, y: 0 }}
            explosionSpeed={300}
            fallSpeed={2000}
            colors={['#ff0000', '#00ff00', '#0000ff']}
          />
        </View>
      </Modal>
      <Modal visible={showModal3} animationType="slide" transparent={true}>
        <View style={styles.successContainer}>
          <Text style={styles.successText}>失败</Text>
          <Image
            source={require('./bear2.gif')}
            style={{ width: 400, height: 400 }}
          />
          <CustomButton title="back" onPress={handleCloseModal3} />
        </View>
      </Modal>
    </View>
  );
};







// 红汤页面组件
const RedSoupScreen = ({ navigation }:Props) => {
  const [showModal, setShowModal] = useState(false);
  const [selectedType, setSelectedType] = useState('');

  const showConfirmation = (type: string) => {
    setSelectedType(type);
    setShowModal(true); // 显示弹窗
    isDataFetched=false;
  };

  const handleConfirmation = (choice: string) => {
    setShowModal(false);
    if (choice === 'yes') {
      if (selectedType === '奇幻') {
        navigation.navigate('Random_RedFantasy');
      } else if (selectedType === '搞笑') {
        navigation.navigate('Random_RedFunny');
      } else if (selectedType === '亲情') {
        navigation.navigate('Random_RedLove');
      } else if (selectedType === '变态') {
        navigation.navigate('Random_RedLove');
      }
    } else {//此处未实现
      if (selectedType === '奇幻') {
        navigation.navigate('ClearFantasy_Tangmian');
      } else if (selectedType === '搞笑') {
        navigation.navigate('ClearFunny_Tangmian');
      } else if (selectedType === '亲情') {
        navigation.navigate('ClearLove_Tangmian');
      }
    }
  };

  return (
    <View style={styles.container}>
      <TouchableOpacity
        style={[styles.button, styles.redButton, styles.buttonWithMargin]}
        onPress={() => showConfirmation('变态')}
      >
        <Text style={styles.buttonText1}>变态</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.button, styles.redButton, styles.buttonWithMargin]}
        onPress={() => showConfirmation('奇幻')}
      >
        <Text style={styles.buttonText1}>奇幻</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.button, styles.redButton, styles.buttonWithMargin]}
        onPress={() => showConfirmation('搞笑')}
      >
        <Text style={styles.buttonText1}>搞笑</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={[styles.button, styles.redButton, styles.buttonWithMargin]}
        onPress={() => showConfirmation('亲情')}
      >
        <Text style={styles.buttonText1}>亲情</Text>
      </TouchableOpacity>

      {showModal && (
        <Modal transparent={true} animationType="slide">
          <View style={styles.modal}>
            <Text style={[styles.modalText, styles.boldText]}>是否随机选择汤底？</Text>
            <Text style={[styles.modalText, styles.boldText]}>当前选择: {selectedType}</Text>
            <View style={styles.modalButtons}>
              <TouchableOpacity
                style={styles.modalButton}
                onPress={() => handleConfirmation('yes')}
              >
                <Text style={styles.modalButtonText}>是</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={styles.modalButton}
                onPress={() => handleConfirmation('no')}
              >
                <Text style={styles.modalButtonText}>否</Text>
              </TouchableOpacity>
            </View>
          </View>
        </Modal>
      )}
    </View>
  );
};





const HomeScreen = ({navigation}: Props) => {
  const [showAlert, setShowAlert] = useState(false);

  const handleNavigateTosoup = () => {
    navigation.navigate('Soup');
  };

  const handleNavigateTodraw = () => {
    setShowAlert(true); // 显示弹窗
  };

  const handleAlertOk = () => {
    setShowAlert(false); // 关闭弹窗
    navigation.navigate('Draw'); // 跳转到Draw页面
  };
  return (
    <View style={styles.container}>
       <View style={styles.logoContainer2}>
        <Text style={styles.logo2}>破冰</Text>
      </View>
      <View style={styles.buttonContainer2}>
        <TouchableOpacity style={styles.button2} onPress={handleNavigateTosoup}>
          <Image source={require('./turtle.png')} style={styles.buttonIcon} />
        </TouchableOpacity>
        <Text style={styles.textBelowButtonText}>海龟汤</Text>
        <TouchableOpacity style={styles.button2} onPress={handleNavigateTodraw}>
          <Image source={require('./draw.png')} style={styles.buttonIcon} />
        </TouchableOpacity>
        <Text style={styles.textBelowButtonText}>你画你的，我猜我的</Text> 
      </View>
       {/* 弹窗提示关卡越来越难 */}
       {showAlert && (
        <View style={styles.alertContainer}>
          <Text style={styles.alertText}>关卡越到后面越难哦~</Text>
          <Text style={styles.alertText}>和你的好朋友加油通关吧！！</Text>
          <TouchableOpacity style={styles.alertButton} onPress={handleAlertOk}>
            <Text style={styles.alertButtonText}>确定</Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
};

const CustomSoupScreen = ({ navigation }:Props) => {
  const [soupTitle, setSoupTitle] = useState('');
  const [soupContent, setSoupContent] = useState('');
  const [soupType, setSoupType] = useState('');
  const [subType, setSubType] = useState('');

  const typeMapping: { [key: string]: string } = {
    'RedSoup': 'red',
    'ClearSoup': 'clear',
    '奇幻': 'fantasy',
    '搞笑': 'funny',
    '亲情': 'love',
    '变态': 'meta',
  };

  const handleSaveSoup = async () => {
    if (soupTitle && soupContent && soupType && subType) {
      const tableName = `${typeMapping[soupType]}${typeMapping[subType]}`; // 根据映射关系构建表名
      try {
        const response = await fetch(`${SERVER_URL}/save_soup`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            table_name: tableName,
            soup_title: soupTitle,
            soup_content: soupContent,
          }),
        });
        const data = await response.json();
        if (response.ok) {
          Alert.alert('成功', data.message, [{ text: 'OK', onPress: () => navigation.goBack() }]);
        } else {
          Alert.alert('错误', data.error || '保存失败，请稍后再试');
        }
      } catch (error) {
        console.error('保存失败:', error);
        Alert.alert('错误', '保存失败，请稍后再试');
      }
    } else {
      Alert.alert('输入不完整', '请输入汤面、汤底和选择海龟汤类型');
    }
  };

  const handleSoupTypePress = (type:string) => {
    setSoupType(type);
    setSubType(''); // 重置子类型
  };

  const handleSubTypePress = (type:string) => {
    setSubType(type);
  };

  const windowHeight = Dimensions.get('window').height;

  const localStyles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      paddingHorizontal: 20,
      height: windowHeight,
    },
    label: {
      fontSize: 18,
      fontWeight: 'bold',
      marginBottom: 10,
    },
    input: {
      width: '100%',
      height: 100,
      borderWidth: 1,
      borderColor: '#ccc',
      borderRadius: 5,
      paddingHorizontal: 10,
      marginBottom: 20,
    },
    buttonContainer: {
      marginTop: 20,
      width: '100%',
    },
    button: {
      backgroundColor: '#84AE80',
      padding: 10,
      marginVertical: 5,
      borderRadius: 5,
      alignItems: 'center',
    },
    buttonText: {
      color: '#fff',
      fontSize: 16,
    },
    selectedButton: {
      backgroundColor: '#567D50',
    },
  });

  return (
    <ScrollView contentContainerStyle={localStyles.container}>
      <Text style={localStyles.label}>汤面:</Text>
      <TextInput
        style={localStyles.input}
        value={soupTitle}
        onChangeText={setSoupTitle}
        placeholder="输入汤面"
        multiline={true}
        numberOfLines={4}
      />
      <Text style={localStyles.label}>汤底:</Text>
      <TextInput
        style={localStyles.input}
        value={soupContent}
        onChangeText={setSoupContent}
        placeholder="输入汤底"
        multiline={true}
        numberOfLines={4}
      />
      <Text style={localStyles.label}>选择海龟汤类型:</Text>
      <TouchableOpacity
        style={[localStyles.button, soupType === 'RedSoup' && localStyles.selectedButton]}
        onPress={() => handleSoupTypePress('RedSoup')}
      >
        <Text style={localStyles.buttonText}>红汤</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={[localStyles.button, soupType === 'ClearSoup' && localStyles.selectedButton]}
        onPress={() => handleSoupTypePress('ClearSoup')}
      >
        <Text style={localStyles.buttonText}>清汤</Text>
      </TouchableOpacity>
      {soupType === 'RedSoup' && (
        <>
          <Text style={localStyles.label}>选择红汤子类型:</Text>
          <TouchableOpacity
            style={[localStyles.button, subType === '奇幻' && localStyles.selectedButton]}
            onPress={() => handleSubTypePress('奇幻')}
          >
            <Text style={localStyles.buttonText}>奇幻</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[localStyles.button, subType === '搞笑' && localStyles.selectedButton]}
            onPress={() => handleSubTypePress('搞笑')}
          >
            <Text style={localStyles.buttonText}>搞笑</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[localStyles.button, subType === '亲情' && localStyles.selectedButton]}
            onPress={() => handleSubTypePress('亲情')}
          >
            <Text style={localStyles.buttonText}>亲情</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[localStyles.button, subType === '变态' && localStyles.selectedButton]}
            onPress={() => handleSubTypePress('变态')}
          >
            <Text style={localStyles.buttonText}>变态</Text>
          </TouchableOpacity>
        </>
      )}
      {soupType === 'ClearSoup' && (
        <>
          <Text style={localStyles.label}>选择清汤子类型:</Text>
          <TouchableOpacity
            style={[localStyles.button, subType === '奇幻' && localStyles.selectedButton]}
            onPress={() => handleSubTypePress('奇幻')}
          >
            <Text style={localStyles.buttonText}>奇幻</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[localStyles.button, subType === '搞笑' && localStyles.selectedButton]}
            onPress={() => handleSubTypePress('搞笑')}
          >
            <Text style={localStyles.buttonText}>搞笑</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[localStyles.button, subType === '亲情' && localStyles.selectedButton]}
            onPress={() => handleSubTypePress('亲情')}
          >
            <Text style={localStyles.buttonText}>亲情</Text>
          </TouchableOpacity>
        </>
      )}
      <View style={localStyles.buttonContainer}>
        <Button title="保存海龟汤" onPress={handleSaveSoup} />
      </View>
    </ScrollView>
  );
};

// export default CustomSoupScreen;


const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Soup" component={SoupScreen} />
        <Stack.Screen name="Draw" component={DrawScreen} />
        <Stack.Screen name="ClearSoup" component={ClearSoupScreen} />
        <Stack.Screen name="RedSoup" component={RedSoupScreen} />
        <Stack.Screen name="Random_ClearFantasy" component={Random_ClearFantasyScreen} />
        <Stack.Screen name="Random_ClearFunny" component={Random_ClearFunnyScreen} />
        <Stack.Screen name="Random_ClearLove" component={Random_ClearLoveScreen} />
        <Stack.Screen name="Random_RedFantasy" component={Random_RedFantasyScreen} />
        <Stack.Screen name="Random_RedFunny" component={Random_RedFunnyScreen} />
        <Stack.Screen name="Random_RedLove" component={Random_RedLoveScreen} />
        <Stack.Screen name="Random_RedMeTa" component={Random_RedMeTaScreen} />

        <Stack.Screen name="ClearFunny_Tangmian" component={ClearFunny_TangmianScreen} />
        <Stack.Screen name="ClearFunny" component={ClearFunnyScreen} />

        <Stack.Screen name="SuccessScreen" component={SuccessScreen} />
        <Stack.Screen name="Describe" component={DescribeScreen} />
        <Stack.Screen name="Guess" component={GuessScreen} />
        <Stack.Screen name="CustomSoup" component={CustomSoupScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};
interface DesMessage {
  id: string;
  type: 'text' | 'image';
  content: string;
}
interface RouteParams {
  buttonIndex: number;
}

// Define the type for the route
// type Route = RouteProp<{params: RouteParams}, 'params'>;
const GuessScreen: React.FC<Props> = ({navigation, route }:Props) => {

  const [text, setText] = useState('');
  const [dialogVisible, setDialogVisible] = useState(false);
  const [dialogMessage, setDialogMessage] = useState('');

  const userMessage = route.params?.userMessage;
  const selectedTitle = route.params?.selectedTitle;
  const [attemptsLeft, setAttemptsLeft] = useState(3); // 初始剩余尝试次数为3
  const [gameOver, setGameOver] = useState(false); // 游戏结束标志
  console.log('答案',selectedTitle);

  const sendMessage = () => {
    if (text.trim().length > 0 && !gameOver) {
      const inputMessage = text.trim().toLowerCase();
      const isCorrect = inputMessage === selectedTitle.toLowerCase();

      if (isCorrect) {
        setDialogMessage('答案正确！恭喜你！通关啦！');
        setDialogVisible(true);
        setGameOver(true); // 设置游戏结束
      } else {
        const remainingAttempts = attemptsLeft - 1;
        const message = `很遗憾，答案错误！你还有 ${remainingAttempts} 次机会`;
        setDialogMessage(message);
        setDialogVisible(true);
        setAttemptsLeft(remainingAttempts);

        if (remainingAttempts === 0) {
          setGameOver(true); // 如果没有剩余尝试次数，设置游戏结束
        }
      }
      setText('');
    }
  };

  const handleConfirm = () => {
    setDialogVisible(false);
    if (gameOver) {
      navigation.navigate('Draw'); // 游戏结束后跳转到 Draw 页面
    }
  };

  return (
    <View style={styles.guecontainer}>
      {/* 顶部显示 buttonIndex */}
      <View style={styles.guetopBar}>
        <Text style={styles.guebuttonIndexText}>
          Button Index: {buttonIndex}
        </Text>
      </View>

      {/* 屏幕中央固定图片 */}
      <View style={styles.gueimageContainer}>
        <Image source={{ uri: userMessage }} style={styles.gueimage} />
      </View>

      {/* 底部输入区域 */}
      <View style={styles.gueinputContainer}>
        <TextInput
          style={styles.gueinput}
          placeholder="请输入内容"
          value={text}
          onChangeText={setText}
        />
        <Button title="发送" onPress={sendMessage} />
      </View>

      {/* 弹出提示框 */}
      <Dialog.Container visible={dialogVisible}>
        <Dialog.Title>结果</Dialog.Title>
        <Dialog.Description>{dialogMessage}</Dialog.Description>
        <Dialog.Button label="确定" onPress={handleConfirm} />
      </Dialog.Container>
    </View>
  );
};
//第一轮 描述方部分
const DescribeScreen: React.FC<Props> = ({ navigation }) => {


  // const [messages, setMessages] = useState<DesMessage[]>([]);
  const [messages, setMessages] = useState('');
  const [text, setText] = useState('');
  const [dialogVisible, setDialogVisible] = useState(false);
  const [userMessage, setUserMessage] = useState('');
  const [selectedTitle, setSelectedTitle] = useState<string>('');
  const [cancelCount, setCancelCount] = useState(0); // 记录取消描述的次数
  const [remainingAttempts, setRemainingAttempts] = useState(2); // 剩余描述次数

  const [data,setData] = useState<YourData[]>([]);
  const fetchData = async () => {
    try {
      
      if (!isDataFetched) {
        const response = await fetch('http:/10.0.2.2:5000/level1');
        const jsonData = await response.json();
        setData(jsonData);
        // setSelectedTitle(jsonData)
        isDataFetched = true;
        console.log(isDataFetched);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  interface YourData {
    title: string; // 假设 column1 是一个字符串
    // 可以添加其他列...
  }
  

  fetchData(); // Fetch data on component mount

  interface DesMessage {
    id: string;
    type: string;
    content: string;
  }
  // Function to send user message to backend
  const sendToBackend = async () => {
    try {
        console.log('Message sent to backend:', text);
       
        const response = await fetch('http:/10.0.2.2:5000/receive_data2', {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json',
            },
          body: JSON.stringify({ message: text }), // 使用输入框中的文本作为消息
        });
       
        if (response.ok) {
            const responseData = await response.json();
            console.log('Response from backend:', responseData); // 输出从后端返回的响应数据
            // setUserMessage(responseData);
            handleBackendResponse(responseData);
            console.log('Response from backend:', userMessage); // 输出从后端返回的响应数据
           
        } else {
            console.error('Request failed with status:', response.status);
        }
    } catch (error) {
        console.error('Error sending message to backend:', error);
    }
};

  const handleBackendResponse = (responseData: { response: string }) => {
    console.log('Response from backend2:', responseData); // 可以输出整个后端返回的数据对象
    const responseMessage: DesMessage = {
      id: Math.random().toString(),
      type: 'image',
      content: responseData.response, 
    };
    setText(text)
    setMessages(responseMessage.content.toString());
    setUserMessage(responseMessage.content.toString());
    setDialogVisible(true); 
    
  };

  useEffect(() => {
  if (userMessage) {
    setDialogVisible(true);
    console.log('状态',dialogVisible);
    console.log('Response from backend21:', userMessage);
    console.log('Response from backend22:', userMessage);
    console.log('Response from backend23:', userMessage);
    console.log('Response from backend23:', typeof(userMessage));
    console.log('Response from backend23:', typeof(userMessage));
    // // setDialogVisible(true); // 当 userMessage 更新时显示提示框
  }
}, [userMessage]);

  // 点击确定按钮时的处理函数
  const handleConfirm = () => {
    if (data.length > 0) {
      console.log('data:',data);
      const item = data[0]; // Assuming you want to use the first item in data
      console.log('item:',item)
      setSelectedTitle(item.title);
      navigation.navigate('Guess', { userMessage, selectedTitle: item.title });
    } else {
      console.error('No data available');
    }
  };

  const handleCancel = () => {

    if (cancelCount < 2) {
      setCancelCount(cancelCount + 1);
      setRemainingAttempts(3 - (cancelCount+1)); // 更新剩余描述次数
      const responseMessage = {
        id: Math.random().toString(),
        type: 'image',
        content: './bear.jpg', // 当取消次数未达到限制时显示的图片路径
      };
      setUserMessage(null);
      setMessages(responseMessage.content.toString());
      setDialogVisible(false);
    } 
    else {
      // 超过两次取消，显示固定的图片路径
      const item = data[0]; // Assuming you want to use the first item in data
      console.log('item:',item)
      setSelectedTitle(item.title);
      navigation.navigate('Guess', { userMessage, selectedTitle: item.title });
    }
  };

  const renderMessage = ({ item }: { item: DesMessage }) => {
    if (item.type === 'text') {
      return (
        <View style={styles.destextMessage}>
          <Text style={styles.desmessageText}>{item.content}</Text>
        </View>
      );
    } else if (item.type === 'image') {
      return (
        <View style={styles.desimageMessage}>
          <Image
            source={{ uri: item.content }} // Ensure this path is correct
            style={styles.desmessageImage}
          />
        </View>
      );
    }
    return null;
  };

  
  

  return (
    <View style={styles.descontainer}>
      {/* 顶部显示 buttonIndex */}
      <View style={styles.destopBar}>
        {data.map((item, index) => (
          <Text style={styles.desbuttonIndexText} key={index}>
            {item.title}
            {/* Button Index: {buttonIndex} */}
         </Text>
        ))}
      </View>

      <View style={styles.rulesContainer}>
        <Text style={styles.rulesText2}>
          你画你的，我猜我的-游戏规则：
        </Text>
        <Text style={styles.rulesText2}>
          描述方根据选择关卡的题目进行描述
        </Text>
        <Text style={styles.rulesText2}>
          描述时不能出现题目中出现的字
        </Text>
        <Text style={styles.rulesText2}>
          描述者有三次机会选择是否显示当前图片
        </Text>
        <Text style={styles.rulesText2}>
          猜测方根据生成的图片输入答案，答案正确则通关
        </Text>
        
      </View>

      {/* 聊天区域 */}
      <FlatList
        data={messages}
        renderItem={renderMessage}
        keyExtractor={(item) => item.id}
        contentContainerStyle={styles.deschatContainer}
      />

      {/* 底部输入区域 */}
      <View style={styles.desinputContainer}>
        <TextInput
          style={styles.desinput}
          placeholder="请输入内容"
          value={text}
          onChangeText={setText}
        />
        <Button title="发送" onPress={sendToBackend} />
      </View>

      {/* 弹出提示框 */}
      <Dialog.Container visible={dialogVisible}>
        <Dialog.Title>图片生成完毕！</Dialog.Title>
        <Dialog.Description>
          {remainingAttempts > 0
            ? `还剩余 ${remainingAttempts} 次描述机会`
            : '您已经超过描述次数限制'}
        </Dialog.Description>
        <View style={styles.desdialogContent}>
          {/* <Image
            source={require('uri')} // Ensure this path is correct
            style={styles.desdialogImage}
          /> */}
          {/* <Image source={{ uri: userMessage?.content }} style={{width:100,height:150}}/> */}
          <Image source={{ uri:userMessage}} style={{width:150,height:150}}/>
          {/* <Image source={{ uri:'https://ai-painting-image.vivo.com.cn/ai-painting/763783fbe7b7e25498f85f2faf8fc57c1eeeba54-0.jpg' }} style={{width:100,height:150}}/> */}
          <Text>确定选择这张图片吗？</Text>
        </View>
        <Dialog.Button label="取消" onPress={handleCancel} />
        <Dialog.Button label="确定" onPress={handleConfirm} />
      </Dialog.Container>
    </View>
  );
};

const DrawScreen = ({navigation}: Props) => {
  const handleButtonPress = (i:number) => {
    // 导航到 DescribeScreen 
    buttonIndex = i;
    navigation.navigate('Describe');
  };
  const renderButtons = () => {
    const buttons = [];
    for (let i = 1; i <= 9; i++) {
      buttons.push(
        <TouchableOpacity
          key={i}
          style={styles.drawbutton}
          onPress={() => handleButtonPress(i)}>
          <Text style={styles.drawbuttonText}>{i}</Text>
        </TouchableOpacity>,
      );
    }
    return buttons;
  };

  return (
    <View style={styles.drawcontainer}>
      <View style={styles.drawbuttonContainer}>{renderButtons()}</View>
    </View>
  );
};
const SoupScreen = ({ navigation }: { navigation: NavigationScreenProp<any, any> }) => {
  const handleRedSoupPress = () => {
    navigation.navigate('RedSoup');
  };

  const handleClearSoupPress = () => {
    navigation.navigate('ClearSoup');
  };

  const handleCustomSoupPress = () => {
    navigation.navigate('CustomSoup'); // 导航到 'CustomSoup' 屏幕
  };

  return (
    <View style={styles.backcontainer}>
       <ImageBackground
              source={require('./soupbackground1.png')}
              resizeMode='cover'
              style={{ flex: 1, width: '100%', height: '100%' }}>
              <View style={styles.container}>
                <View style={styles.logoContainer}>
                  <Text style={styles.logo}>海龟汤</Text>
                </View>
                <View style={styles.buttonContainer}>
                  <TouchableOpacity style={[styles.button, styles.leftButton]} onPress={handleClearSoupPress}>
                    <Text style={styles.buttonText}>清汤</Text>
                  </TouchableOpacity>
                  <TouchableOpacity style={[styles.button, styles.rightButton]} onPress={handleRedSoupPress}>
                    <Text style={styles.buttonText}>红汤</Text>
                  </TouchableOpacity>
                   <TouchableOpacity style={[styles.button, styles.customButton]} onPress={handleCustomSoupPress}>
                                <Text style={styles.customButtonText}>自定义海龟汤</Text>
                   </TouchableOpacity>
                </View>
              </View>
            </ImageBackground>
          </View>
        );
      };


// export default SoupScreen;

const styles = StyleSheet.create({
  guecontainer: {
    flex: 1,
  },
  guetopBar: {
    padding: 10,
    backgroundColor: '#e9f1f6',
    alignItems: 'center',
  },
  guebuttonIndexText: {
    fontSize: 16,
    // backgroundColor: '#81cac4',
    color: '#392f41',
  },
  gueimageContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff2df',
  },
  gueimage: {
    width: 200,
    height: 200,
  },
  gueinputContainer: {
    flexDirection: 'row',
    padding: 10,
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  gueinput: {
    flex: 1,
    height: 40,
    borderColor: '#cccccc',
    borderWidth: 1,
    borderRadius: 5,
    paddingHorizontal: 10,
    marginRight: 8,
  },
  desdialogContent: {
    alignItems: 'center',
    marginBottom: 20,
  },
  desdialogImage: {
    width: 100,
    height: 100,
    marginBottom: 10,
  },
  descontainer: {
    flex: 1,
  },
  destopBar: {
    padding: 16,
    backgroundColor: 'lightblue',
    alignItems: 'center',
  },
  desbuttonIndexText: {
    fontSize: 18,
    fontWeight: 'bold',
    color:'white',
  },
  deschatContainer: {
    flexGrow: 1,
    padding: 16,
  },
  destextMessage: {
    alignSelf: 'flex-end',
    backgroundColor: '#dcf8c6',
    borderRadius: 10,
    padding: 10,
    marginVertical: 5,
    maxWidth: '70%',
  },
  desimageMessage: {
    alignSelf: 'flex-start',
    backgroundColor: '#f0f0f0',
    borderRadius: 10,
    padding: 10,
    marginVertical: 5,
  },
  desmessageText: {
    fontSize: 16,
  },
  desmessageImage: {
    width: 150,
    height: 150,
    borderRadius: 10,
  },
  desinputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    backgroundColor: '#f8f8f8',
    borderTopWidth: 1,
    borderTopColor: '#e0e0e0',
  },
  desinput: {
    flex: 1,
    height: 40,
    borderColor: '#cccccc',
    borderWidth: 1,
    borderRadius: 5,
    paddingHorizontal: 10,
    marginRight: 8,
  },
  drawcontainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#e6d0c2',
  },
  drawbuttonContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'center',
    alignItems: 'center',
  },
  drawbutton: {
    width: '25%',
    aspectRatio: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#ba6e6e',
    margin: 15,
    borderRadius: 10,
  },
  drawbuttonText: {
    fontSize: 30,
    color: '#e6d0c2',
  },
  backcontainer: {
      flex:1,
      justifyContent:'center',
      resizeMode:'cover',
  },
  background: {
    flex: 1,
    resizeMode: 'cover', // 保持图片比例铺满整个屏幕
    justifyContent: 'center', // 垂直居中
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },

  alertContainer: {
    backgroundColor: 'rgb(200, 220, 248)', // 弹窗背景色
    padding: 20,
    borderRadius: 10,
    alignItems: 'center',
    elevation: 5, // Android阴影效果
    shadowColor: '#000000', // iOS阴影颜色
    shadowOffset: { width: 0, height: 2 }, // iOS阴影偏移量
    shadowOpacity: 0.25, // iOS阴影透明度
    shadowRadius: 3, // iOS阴影圆角
    position:'absolute',
    top:'37%',
    height:150,
    width:250,

  },
  alertText: {
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 10,
    color: 'white',
  },
  alertButton: {
    height:42,
    backgroundColor: 'white', // 确定按钮背景色
    paddingVertical: 10,
    paddingHorizontal: 20,
    borderRadius: 5,
    marginTop: 10,
  },
  alertButtonText: {
    color: 'rgb(197, 240, 240)', // 确定按钮文字颜色
    fontSize: 16,
    textAlign: 'center',
  },

  logoContainer2: {
    position: 'absolute',
    top: 20,
    left: 130,
  },
  logoContainer: {
    marginBottom: 200,
  },
  logo2: {
    fontFamily: 'YourCustomFont',
    fontSize: 70,
    fontWeight: 'bold',
    color: 'rgb(197, 240, 248)',
  },

  logo: {
    fontSize: 60,
    fontWeight: 'bold',
    color: 'rgb(84, 174, 128)',
  },
  buttonContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 20,
  },

  button: {
    width: 100,
    height: 50,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom:200,
  },

  redButton: {
    width:180,
    height:70,
    backgroundColor: 'rgb(254,156,171)',
    borderRadius:50,
  },
  clearButton: {
    width:180,
    height:70,
    backgroundColor: 'lightblue',
    borderRadius:50,
  },
  leftButton: {
    borderTopLeftRadius: 100,
    borderBottomLeftRadius: 100,
    backgroundColor: 'lightblue',
  },
  rightButton: {
    borderTopRightRadius: 100,
    borderBottomRightRadius: 100,
    backgroundColor: 'rgb(254,156,171)',
  },
  //这是新加的按钮

customButton: {
  backgroundColor:  'rgb(84, 174, 128)',
  borderRadius: 30, // 更圆的角
  shadowColor: '#000',
  shadowOffset: { width: 0, height: 2 },
  shadowOpacity: 0.8,
  shadowRadius: 2,
  elevation: 5, // 阴影效果
  width: 200,
  height: 55,
  alignSelf: 'center', // 居中对齐
  position: 'absolute', // 绝对定位
  marginBottom: 0, // 底部边距为0
  paddingVertical: 15,
  alignItems: 'center', // 水平方向上居中对齐内容
},

  buttonWithMargin: {
    marginBottom: 30,
  },
  buttonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
  },
  buttonText1: {
    color: '#fff',
    fontSize: 25,
    fontWeight: 'bold',
  },
   customButtonText: {
      color: '#fff', // 未知
      fontSize: 18,
       fontWeight: 'bold',
    },
  buttonContainer2: {
    left:0,
    alignItems: 'center',
    flexDirection: 'column', // 设置按钮容器的flex方向为竖直方向
    justifyContent: 'center',
  },
  button2: {
    width: 100,
    height: 100,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'lightblue',
    borderRadius: 20,
    marginHorizontal: 10,
    marginBottom:5,
  },
  buttonText2: {
    fontSize: 18,
    fontWeight: 'bold',
    marginLeft: 10,
    marginBottom:20,
  },
  buttonIcon: {
    width: 100,
    height: 100,
    marginRight: 10,
    borderRadius: 20,
    marginHorizontal: 10,
},
textBelowButtonText: {
  fontSize: 20,
  marginBottom:25,
},

  modal: {
    position: 'absolute',
    backgroundColor: 'rgb(235, 250, 223)',
    padding: 20,
    borderRadius: 10,
    alignItems: 'center',
    alignSelf: 'center',
    top: '50%',
    zIndex: 1,
    width: 280,
  },
  modalText: {
    marginBottom: 20,
    fontSize: 18,
    color: 'rgb(122, 186, 69)',
  },
  modalButtons: {
    flexDirection: 'row',
  },
  modalButton: {
    backgroundColor: 'rgb(199, 250, 186)',
    borderRadius: 10,
    paddingVertical: 10,
    paddingHorizontal: 20,
    marginHorizontal: 10,
  },
  modalButtonText: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#fff',
  },
  topModal: {
    top: '39.5%', // 调整这个值来控制距离屏幕顶部的距离
  },
  boldText: {
    fontWeight: 'bold',
  },
  header: {
    backgroundColor: '#E1B7C9',
    padding: 10,
    alignItems: 'center',
    flexDirection: 'row',
  },
  headerText: {
    fontWeight: 'bold',
    fontSize: 18,
    flex: 9,
    color: 'white',
  },
  conversation: {
    flex: 1,
    paddingHorizontal: 20,
    paddingTop: 20,
    paddingBottom: 10,
  },
  userMessage: {
    marginBottom: 10,
    padding: 10,
    backgroundColor: '#F9F1DB',
    alignSelf: 'flex-end',
    borderRadius: 5,
  },
  botMessage: {
    marginBottom: 10,
    padding: 10,
    backgroundColor: '#B1E1A3',
    color: '#FFFFFF',
    alignSelf: 'flex-start',
    borderRadius: 5,
  },
  answerButton: {
    marginBottom: 20,
    flexDirection: 'row',
    marginLeft: 120,
    marginRight: 120,
    justifyContent: 'space-between',
  },
  inputBox: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 10,
    paddingBottom: 10,
    backgroundColor: '#f0f0f0',
  },
  input: {
    flex: 1,
    paddingVertical: 5,
    paddingHorizontal: 10,
    borderRadius: 5,
    backgroundColor: '#ffffff',
    marginRight: 10,
  },
  welcomeContainer: {
    paddingHorizontal: 20,
    paddingTop: 20,
    paddingBottom: 10,
  },
  welcomeText: {
    fontWeight: 'bold',
    fontSize: 16,  // 较小的字体大小
    marginBottom: 10,
    color: 'rgba(136, 136, 136, 0.8)',  // 灰色文本颜色，透明度为 0.8
  },
  ruleText: {
    marginBottom: 5,
    fontSize: 12,  // 较小的字体大小
    color: 'rgba(136, 136, 136, 0.8)',  // 灰色文本颜色，透明度为 0.8
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  modalContent: {
    backgroundColor: '#ffffff',
    padding: 20,
    borderRadius: 10,
    height: 400,
    width: 400,
  },
  buttonbox: {
    flexDirection: 'row',
    marginRight: 10,
    justifyContent: 'space-around',
    alignItems: 'flex-end',
    flex: 2,
    marginLeft: 1,
  },
  input_guessstory: {
    flex: 6,
  },
  button3: {
    padding: 10,
    backgroundColor: '#FFFFEB',
    borderRadius: 5,
  },
  buttonText3: {
    color: '#FB9A99',
    fontSize: 16,
    fontWeight: 'bold',
  },
  successContainer: {
    flex: 1,
    justifyContent: 'space-around',
    alignItems: 'center',
    backgroundColor: '#FB9A99',
  },
  successText: {

    fontSize: 48,
    fontWeight: 'bold',
    color: '#FFFFEB',
  },
  rulesContainer: {
    position:'absolute',
    top:'20%',
    
    
  },
  rulesText2: {
    fontSize: 16,
    fontWeight: 'bold',
    textAlign: 'center',
    lineHeight: 50,
    color:'rgb(160,180,190)',
    left:30,

  },

});

export default App;
